package com.ljfiction.book.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.ljfiction.book.Baner.BookListListBean;
import com.ljfiction.book.Baner.FistHom;
import com.ljfiction.book.Baner.HomhotnewListRecycla;
import com.ljfiction.book.Baner.XianmianBean;
import com.ljfiction.book.Dialog.CreateTishiDialog;
import com.ljfiction.book.MyView.BannerView;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.MyView.NoScrollGridView;
import com.ljfiction.book.R;
import com.ljfiction.book.activitys.BiaoqianActivity;
import com.ljfiction.book.activitys.BookDetailsActivity;
import com.ljfiction.book.activitys.ClassfimuchActivity;
import com.ljfiction.book.activitys.RecommendActivity;
import com.ljfiction.book.adapter.BannerBaseAdapter;
import com.ljfiction.book.adapter.HothuanyihuanGridViewAdapter;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.AppUtils;
import com.ljfiction.book.tools.EventTool;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.Tool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;

import cn.iwgang.countdownview.CountdownView;

import okhttp3.Call;
import okhttp3.Response;


/**
 * Created by Administrator on 2017/7/6.
 */
public class HomHotFragment extends BaseFragment implements View.OnClickListener {
    private TextView muchxiaobiantuijian;
    private CountdownView xianmiandaojishi;
    private List<FistHom.DataBean.HostXiaoBianRecommendBean> booklistXiaobian = new ArrayList<>();
    private List<XianmianBean.DataBeanX.DataBean> boolistXianmian = new ArrayList<>();
    private List<FistHom.DataBean.BooklableListBean> biaoqianlist = new ArrayList<>();
    private List<BookListListBean.DataBean.ListBean> booknewlist = new ArrayList<>();
    private Context context;
    private BannerView bannerView;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView heavyGridView;
    private RecyclerView hotxianmianGridview;
    private NoScrollGridView hotbiaoqiangridview;
    private RecyclerView ptrl;
    private NestedScrollView mscrollView;

    private BaseQuickAdapter adapter;
    private List<FistHom.DataBean.PictureCarouselVersionTowBean> datas = new ArrayList<>();
    private LinearLayout huanyihuanimageView;
    private HothuanyihuanGridViewAdapter hothuanyihuanGridViewAdapter;
    private HashSet<Integer> intlist = new HashSet<Integer>();
    private List<Integer> listint = new ArrayList<>();
    private int page = 1;
    private FistHom f;
    private ImageView advertisingimage; //公告
    private Intent intent, intentxiaobiann, intentbiaoqian;
    private BaseQuickAdapter xianmianAdapter;
    private BaseQuickAdapter hotxiaobianAdapter;
    private BookListListBean nmb;
    private XianmianBean x;
    //private NoBackgLodDialog mloding;
    private boolean isfirst = false;//提示框

    public static HomHotFragment newInstance(FistHom f, boolean isfirst) {
        HomHotFragment newFragment = new HomHotFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("fistHom", f);
        bundle.putBoolean("isfirst", isfirst);
        newFragment.setArguments(bundle);
        return newFragment;

    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppUtils.init(getContext());
        Bundle args = getArguments();
        if (args != null) {
            f = (FistHom) args.getSerializable("fistHom");
            isfirst = args.getBoolean("isfirst");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View vi = inflater.inflate(R.layout.fragment_homho, container, false);
        refreshLayout =  vi.findViewById(R.id.refresh_hothom);
        bannerView =  vi.findViewById(R.id.bannerView_hot);
        heavyGridView =vi.findViewById(R.id.heavyGridView);
        hotxianmianGridview =  vi.findViewById(R.id.hotxianmian_gridview);
        hotbiaoqiangridview =  vi.findViewById(R.id.hotbiaoqiangridview);
        ptrl = vi.findViewById(R.id.newBookpulltoRefreshListview);
        mscrollView =  vi.findViewById(R.id.hot_scrollView);
        huanyihuanimageView =  vi.findViewById(R.id.huayihuan_homhot);
        xianmiandaojishi = vi.findViewById(R.id.daojishi);
        muchxiaobiantuijian =  vi.findViewById(R.id.muchxiaobiantuijian);
        advertisingimage = vi.findViewById(R.id.advertisingiamge);
        context = getActivity();
        intent = new Intent(context, BookDetailsActivity.class);
        intentxiaobiann = new Intent(context, RecommendActivity.class);
        intentbiaoqian = new Intent(context, ClassfimuchActivity.class);
        intView();
        if (f == null) {
            intData();
        } else {
            toData();
        }
        intXianmian();
        //请求最新书籍
        gethotbooklist();
        intEvent();
        return vi;
    }

    private void gethotbooklist() {
        OkHttpUtils.get(HttpManager.IP + "/hot/getbooklistList/"+page+"/10")

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();

                        try {
                            nmb = gson.fromJson(s, BookListListBean.class);
                            if (nmb.getReturnCode() == 200) {
                                booknewlist.addAll(nmb.getData().getList());
                                adapter.notifyDataSetChanged();

                            }
                            if (nmb.getData().isIsLastPage()) {
                                refreshLayout.finishLoadMore();
                            } else {
                                refreshLayout.finishLoadMore();
                            }
                            refreshLayout.finishRefresh();

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }




public void refreshhotlist(){
    if (adapter!=null){
        booknewlist.clear();
        page=1;
        gethotbooklist();
    }
}
    private void intView() {
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                try {
                    if (nmb.getData().isIsLastPage()) {
                        refreshlayout.finishLoadMore();
                        refreshLayout.setEnableLoadMore(false);
                    } else {
                        page++;
                       gethotbooklist();
                    }
                } catch (Exception e) {
                    refreshlayout.finishLoadMore();
                    e.printStackTrace();
                }

            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                booknewlist.clear();
                page = 1;
                intData();
                gethotbooklist();
                refreshLayout.setEnableLoadMore(true);
            }
        });
        //小编推荐
        heavyGridView.setLayoutManager(new GridLayoutManager(context, 3));
        heavyGridView.setAdapter(hotxiaobianAdapter = new BaseQuickAdapter<FistHom.DataBean.HostXiaoBianRecommendBean, BaseViewHolder>(R.layout.gridview_hotbook, booklistXiaobian) {
            @Override
            protected void convert(BaseViewHolder helper, FistHom.DataBean.HostXiaoBianRecommendBean item) {
                AutoUtils.autoSize(helper.itemView);
                Glide.with(context).load(item.getBookImage()).into((ImageView) helper.getView(R.id.hotbook_imageview));
                helper.setText(R.id.hotbook_writername, item.getWriterName())
                        .setText(R.id.hotbook_bookname, item.getBookName());
            }
        });
        hotxiaobianAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                EventTool.putEvent(context,"点击","点击","3_recommendMoreClick");
                intent.putExtra("bookId", booklistXiaobian.get(position).getBookId() + "");
                context.startActivity(intent);
            }
        });
        //限时免费
        hotxianmianGridview.setLayoutManager(new GridLayoutManager(context, 4));
        hotxianmianGridview.setAdapter(xianmianAdapter = new BaseQuickAdapter<XianmianBean.DataBeanX.DataBean, BaseViewHolder>(R.layout.gridview_hotxianmianbook, boolistXianmian) {
            @Override
            protected void convert(BaseViewHolder helper, XianmianBean.DataBeanX.DataBean item) {
                AutoUtils.autoSize(helper.itemView);
                Glide.with(context).load(item.getBookImage()).into((ImageView) helper.getView(R.id.hotxianmianbook_imageview));
                helper.setText(R.id.hotxianmianbook_writername, item.getWriterName())
                        .setText(R.id.hotxianmianbook_bookname, item.getBookName());
            }
        });
        xianmianAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                intent.putExtra("bookId", String.valueOf(boolistXianmian.get(position).getBookId()));
                context.startActivity(intent);
            }
        });
        xianmiandaojishi.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
            @Override
            public void onEnd(CountdownView cv) {
                intXianmian();
            }
        });
        //换一换标签
        hothuanyihuanGridViewAdapter = new HothuanyihuanGridViewAdapter(biaoqianlist, listint);
        hotbiaoqiangridview.setAdapter(hothuanyihuanGridViewAdapter);
        //最新小说
        ptrl.setLayoutManager(new LinearLayoutManager(context));
        ptrl.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL_LIST));
        ptrl.setAdapter(adapter = new BaseQuickAdapter<BookListListBean.DataBean.ListBean, BaseViewHolder>(R.layout.newbook_hotlist, booknewlist) {
            @Override
            protected void convert(BaseViewHolder helper, BookListListBean.DataBean.ListBean item) {
                AutoUtils.autoSize(helper.itemView);
                Glide.with(context).load(item.getBookImage()).into((ImageView) helper.getView(R.id.newbook_hotlistimage));
                //设置布局管理器
                LinearLayoutManager linearLayou = new LinearLayoutManager(context);
                linearLayou.setOrientation(LinearLayoutManager.HORIZONTAL);
                ((RecyclerView) helper.getView(R.id.recyclerviewbiaoqian)).setLayoutManager(linearLayou);
                ((RecyclerView) helper.getView(R.id.recyclerviewbiaoqian)).setAdapter(new BaseQuickAdapter<BookListListBean.DataBean.ListBean.BooklableListBean, BaseViewHolder>(R.layout.homhotnewrecycal, (item.getBooklableList().size()>4?item.getBooklableList().subList(0,3):item.getBooklableList())) {
                    @Override
                    protected void convert(BaseViewHolder helper, BookListListBean.DataBean.ListBean.BooklableListBean item) {
                        AutoUtils.autoSize(helper.itemView);
                        helper.setText(R.id.lablebordertext, item.getBookLableName()).setTextColor(R.id.lablebordertext, Color.parseColor(item.getBookColor()));
                    }
                });

                helper.setText(R.id.calsshotlist, item.getClassificationName())
                        .setText(R.id.bookName_newlist, item.getBookName())
                        .setText(R.id.writerName_newlist, "作者: " + item.getWriterName())
                        .setText(R.id.jianjie_newlist, item.getBookIntroduction());
            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                intent.putExtra("bookId", String.valueOf(booknewlist.get(position).getBookId()));
                context.startActivity(intent);
            }
        });

    }

    private void intXianmian() {
        OkHttpUtils.get(HttpManager.IP + "/sys-freetimelimit")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson g = new Gson();

                        try {
                            x = g.fromJson(s, XianmianBean.class);
                            if (x.getReturnCode() == 200) {
                                boolistXianmian.clear();
                                boolistXianmian.addAll(x.getData().getData());
                                xianmianAdapter.notifyDataSetChanged();
                                xianmiandaojishi.start(x.getData().getFreetimelimitdate() * 1000);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });

    }

    private void intEvent() {
        muchxiaobiantuijian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(intentxiaobiann);
            }
        });
        advertisingimage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventTool.putEvent(context,"点击","点击","8_activityH5Click");
                try {
                    if (f.getData().getActivityRecommendedPositionList().size() > 0) {
                        if (f.getData().getActivityRecommendedPositionList().get(0).getShowHide() == 0) {
                            if (f.getData().getActivityRecommendedPositionList().get(0).getBookId() > 0) {
                                intent.putExtra("bookId", f.getData().getActivityRecommendedPositionList().get(0).getBookId() + "");
                                context.startActivity(intent);
                            } else {
                                Intent intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                Uri content_url = Uri.parse(f.getData().getActivityRecommendedPositionList().get(0).getDetailsImgAndPageURL());
                                intent.setData(content_url);
                                startActivity(intent);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        hotbiaoqiangridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                intentbiaoqian.putExtra("id", String.valueOf(biaoqianlist.get(listint.get(position)).getId()));
                intentbiaoqian.putExtra("name", biaoqianlist.get(listint.get(position)).getBookLableName());
                context.startActivity(intentbiaoqian);
            }
        });

        huanyihuanimageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testRandom3();
                hothuanyihuanGridViewAdapter.notifyDataSetInvalidated();
                hothuanyihuanGridViewAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.bannerView_hot:
                break;
            case R.id.heavyGridView:
                break;
            case R.id.hotxianmian_gridview:
                break;
            case R.id.hotbiaoqiangridview:
                break;
            case R.id.newBookpulltoRefreshListview:
                break;

        }
    }

    private void intData() {
        OkHttpUtils.get(HttpManager.IP + "/hot/homePageRecommended")

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        mscrollView.setVisibility(View.VISIBLE);
                        Gson g = new Gson();
                        try {
                            f = g.fromJson(s, FistHom.class);
                            refreshLayout.finishRefresh();
                            toData();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void toData() {
        datas.clear();

        try {
            datas.addAll(f.getData().getPictureCarouselVersionTow());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //轮播图
        initBanner();
        booklistXiaobian.clear();
        try {
            booklistXiaobian.addAll(f.getData().getHostXiaoBianRecommend());
        } catch (Exception e) {
            e.printStackTrace();
        }
        hotxiaobianAdapter.notifyDataSetChanged();
        biaoqianlist.clear();
        try {
            biaoqianlist.addAll(f.getData().getBooklableList());
        } catch (Exception e) {
            e.printStackTrace();
        }
        testRandom3();
        hothuanyihuanGridViewAdapter.notifyDataSetChanged();
        try {
            if (f.getData().getActivityRecommendedPositionList().size() > 0) {
                Glide.with(context).load(f.getData().getActivityRecommendedPositionList().get(0).getActivityImgURL()).into(advertisingimage);
            } else {
                advertisingimage.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //第一次进来显示提示
        if (isfirst) {
            isfirst = false;
            new CreateTishiDialog(context);
        }
        if (UserManageBean.isLogin() && UserManageBean.userBean.getsTR() == 1) {
            Tool.xmjaddtishi(context);
            UserManageBean.userBean.setsTR(0);
        }
    }




    private void initBanner() {
        BannerAdapter mAdapter = new BannerAdapter(context);
        mAdapter.setData(datas);
        bannerView.setAdapter(mAdapter);
        mAdapter.setOnPageTouchListener(new BannerBaseAdapter.OnPageTouchListener<FistHom.DataBean.PictureCarouselVersionTowBean>() {
            @Override
            public void onPageClick(int position, FistHom.DataBean.PictureCarouselVersionTowBean bannerBean) {
                EventTool.putEvent(context,"点击","banner"+position,"4_homeBannerClick");
                // 页面点击
                if (bannerBean.getBookId()>0){
                    intent.putExtra("bookId", String.valueOf(bannerBean.getBookId()));
                    startActivity(intent);
                }else {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse(bannerBean.getDetailsImgAndPageURL());
                    intent.setData(content_url);
                    startActivity(intent);
                }

            }

            @Override
            public void onPageDown() {
                // 按下，可以停止轮播
                //   Toast.makeText(BannerActivity.this, "按下", Toast.LENGTH_SHORT).show();
                bannerView.stopAutoScroll();
            }

            @Override
            public void onPageUp() {
                // 抬起开始轮播
                //  Toast.makeText(BannerActivity.this, "抬起", Toast.LENGTH_SHORT).show();
                bannerView.startAutoScroll();
            }
        });
    }


    private class BannerAdapter extends BannerBaseAdapter<FistHom.DataBean.PictureCarouselVersionTowBean> {

        public BannerAdapter(Context context) {
            super(context);
        }

        @Override
        protected int getLayoutResID() {
            return R.layout.item_banner;
        }

        @Override
        protected void convert(View convertView, FistHom.DataBean.PictureCarouselVersionTowBean data) {
            setImage(R.id.pageImage, data.getActivityImgURL(), context);
        }
    }

    //产生随机数
    private void testRandom3() {
        if (biaoqianlist.size() < 10) {
            return;
        }
        intlist.clear();
        listint.clear();
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            int randomInt = random.nextInt(biaoqianlist.size() - 1);

            if (!intlist.contains(randomInt)) {
                intlist.add(randomInt);
                listint.add(randomInt);

            } else {
                i--;

            }
        }

    }

}
